package com.sgcc.fj.pmos.e_fj_home.activity;


import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.sgcc.fj.pmos.arouter.home.HomeArouterPath;
import com.sgcc.fj.pmos.common.base.MvpBaseActivity;
import com.sgcc.fj.pmos.common.bean.EventCenter;
import com.sgcc.fj.pmos.common.utils.ArguConstant;
import com.sgcc.fj.pmos.common.utils.ImmersionBarUtils;
import com.sgcc.ln.pmos.common.widget.TitleBar;
import com.sgcc.pmos.nativesdk.R;
import com.sgcc.fj.pmos.e_fj_home.adapter.UserTypeHisAdapter;
import com.sgcc.fj.pmos.e_fj_home.bean.UserTypeChangeBean;
import com.sgcc.fj.pmos.e_fj_home.bean.UserTypeListBean;
import com.sgcc.fj.pmos.e_fj_home.contract.UserTypeInfoContract;
import com.sgcc.fj.pmos.e_fj_home.presenter.UserTypeInfoPresenter;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * @author rjc
 * @describe 用户身份切换页面
 */

@Route(path = HomeArouterPath.HOME_USERTYPEINFO)
public class UserTypeInfoActivity extends MvpBaseActivity<UserTypeInfoPresenter> implements UserTypeInfoContract.View {
    private TextView tv_gotochange, tv_querynowtype, tv_querytypelist;
    int year = 2022;
    int month = 1;
    @Autowired
    public String userType;
    private TitleBar mTitleBar;
    private TextView tv_time, tv_usertype;
    private LinearLayout liner_time;
    Calendar startDate = Calendar.getInstance();
    Calendar endDate = Calendar.getInstance();
    TimePickerView pvTime;
    boolean showOneBtn = false;

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.activity_usertype_info;
    }

    @Override
    public boolean isBindEventBusHere() {
        return true;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(EventCenter eventCenter) {
        if (eventCenter.getEventCode() == ArguConstant.USER_TYPE_CHANGE) {
            mPresenter.getNowUserType(Calendar.getInstance().get(Calendar.YEAR) + "", Calendar.getInstance().get(Calendar.MONTH) + 1);
        }
    }

    @Override
    protected void initViews() {
        super.initViews();
        mTitleBar = (TitleBar) findViewById(R.id.title_bar);
        mTitleBar.setTitle("身份管理");
        tv_gotochange = findViewById(R.id.tv_gotochange);
        tv_querynowtype = findViewById(R.id.tv_querynowtype);
        tv_querytypelist = findViewById(R.id.tv_querytypelist);

        tv_usertype = findViewById(R.id.tv_usertype);
        tv_time = findViewById(R.id.tv_time);

        liner_time = findViewById(R.id.liner_time);
        ImmersionBarUtils.initBaseBar(this);
        String[] titleList = new String[2];
        titleList[0] = "身份信息";
        titleList[1] = "身份转换记录";
        year = Calendar.getInstance().get(Calendar.YEAR);
        month = Calendar.getInstance().get(Calendar.MONTH);
        tv_gotochange.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (TextUtils.equals(userType, "电网公司代理用户")) {
                    if (month == 3 || month == 6 || month == 9 || month == 12) {
                        ARouter.getInstance()
                                .build(HomeArouterPath.HOME_USERTYPECHANGE)
                                .withInt("year", year)
                                .withInt("month", month)
//                                .withString("yearAndMonth", getNowTime())
                                .navigation();
                    } else {
                        int nextMonth=month;
                        int nextMYear=year;
                        if(nextMonth<3){
                            nextMonth=4;
                        }else if(nextMonth>3&&nextMonth<6){
                            nextMonth=7;
                        }else if(nextMonth>6&&nextMonth<9){
                            nextMonth=10;
                        }
                        else if(nextMonth>9&&nextMonth<12){
                            nextMonth=1;
                            nextMYear++;
                        }
                        ToastUtils.showShort("当前月份不能进行转换，下一个转换窗口期为"+nextMYear+nextMonth+"月");
                    }
                } else {
                    ARouter.getInstance()
                            .build(HomeArouterPath.HOME_USERTYPECHANGE)
                            .navigation();
                }
            }
        });
        tv_querynowtype.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ARouter.getInstance()
                        .build(HomeArouterPath.HOME_USERTYPENOW)
                        .navigation();
            }
        });
        tv_querytypelist.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ARouter.getInstance()
                        .build(HomeArouterPath.HOME_USERTYPEHIS)
                        .navigation();
            }
        });
        Date resultDate = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        tv_time.setText(CalendarToString(getTagetTime()));
        mPresenter.getNowUserType(Calendar.getInstance().get(Calendar.YEAR) + "", Calendar.getInstance().get(Calendar.MONTH) + 1);
        initTimeSelect();
        liner_time.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String time = tv_time.getText().toString();
                if(!TextUtils.isEmpty(time)){
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
                    try {
                        Date newTime = format.parse(time);
                        Calendar calendar1=    Calendar.getInstance();
                        calendar1.setTime(newTime);
                        pvTime.setDate(calendar1);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                pvTime.show();
            }
        });
    }

    @Override
    protected void initData() {
        super.initData();

    }

    private String getNowTime() {
        Date d = new Date();//获取时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");//转换格式
        return sdf.format(d);
    }

    @Override
    public void queryNowUserSuccess(UserTypeListBean.DataDTO bean) {
        if (!TextUtils.isEmpty(bean.getUserType())) {
            if (TextUtils.equals(bean.getUserType(), "电网公司代理用户")) {
                mPresenter.getNextUserType(getNextQuarter());
            } else {
                showOneBtn = false;
                tv_querynowtype.setVisibility(View.VISIBLE);
                tv_querytypelist.setVisibility(View.VISIBLE);
                tv_gotochange.setText("我要转换身份");
                tv_time.setText(CalendarToString(getTagetTime()));
                mPresenter.getTagetUserType(getTagetTime().get(Calendar.YEAR) + "", getTagetTime().get(Calendar.MONTH)+1);
            }
        } else {
          ToastUtils.showShort("身份信息获取失败");
        }


    }

    @Override
    public void queryNowUserFaile() {

    }

    @Override
    public void queryNextUserTypeSuccess(UserTypeChangeBean bean) {
        if (bean != null) {
            if (bean.getStatus() == 0) {
                if (TextUtils.equals(bean.getData().getOriginalText(), "电网公司代理用户")) {
                    tv_querynowtype.setVisibility(View.GONE);
                    tv_querytypelist.setVisibility(View.GONE);
                    tv_gotochange.setText("我要入市");
                    showOneBtn = true;
                } else {
                    tv_querynowtype.setVisibility(View.VISIBLE);
                    tv_querytypelist.setVisibility(View.VISIBLE);
                    tv_gotochange.setText("我要转换身份");
                    tv_time.setText(CalendarToString(getTagetTime()));
                    mPresenter.getTagetUserType(getTagetTime().get(Calendar.YEAR) + "", getTagetTime().get(Calendar.MONTH)+1);
                    showOneBtn = false;
                }
            } else {
                ToastUtils.showShort(bean.getMessage());
            }

        } else {
            ToastUtils.showShort("数据返回有误");
        }


    }

    @Override
    public void queryNextUserTypeFaile() {

    }

    @Override
    public void getTagetUserTypeSuccess(UserTypeChangeBean bean) {
        if (bean != null) {
            if (bean.getStatus() == 0) {
                if (!TextUtils.equals(bean.getData().getOriginalText(), "电网公司代理用户")) {
                    tv_usertype.setText(bean.getData().getOriginalText());
                }
            } else {
                tv_usertype.setText("暂无相关信息");
                ToastUtils.showShort(bean.getMessage());
            }

        } else {
            ToastUtils.showShort("数据返回有误");
        }

    }

    @Override
    public void getTypeListSuccess(UserTypeListBean.DataDTO bean) {
        if (bean != null) {
            if (!TextUtils.equals(bean.getUserType(), "3")) {
                tv_usertype.setText(UserTypeHisAdapter.getUserType(bean.getUserType()));
            }
        }
    }

    @Override
    protected UserTypeInfoPresenter createPresenter() {
        return new UserTypeInfoPresenter();
    }


    private void initTimeSelect() {
        //正确设置方式 原因：注意事项有说明
        Calendar calendar = Calendar.getInstance();
        // 获取当前年
        int year = calendar.get(Calendar.YEAR);
        // 获取当前月
        int month = calendar.get(Calendar.MONTH) + 1;
        startDate.set(2021, 0, 1);
        endDate.set(2099, 11, 1);
        //时间选择器
        pvTime = new TimePickerBuilder(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                String time = TimeUtils.date2String(date, "yyyy-MM");
                tv_time.setText(time);
                mPresenter.getTagetUserType(StringToClender(date).get(Calendar.YEAR) + "", StringToClender(date).get(Calendar.MONTH)+1);
            }
        }).setType(new boolean[]{true, true, false, false, false, false})
                .setDecorView((ViewGroup) getWindow().getDecorView().findViewById(android.R.id.content))
                .setRangDate(startDate, endDate)
                .build();
    }

    private Calendar getTagetTime() {
        Calendar calendar = Calendar.getInstance();

        int day = Calendar.getInstance().get(Calendar.DATE);
        if (day < 15) {
//            tagetTime = DateUtils.getMonthBackString(1, "yyyy-MM");
            calendar.add(Calendar.MONTH, 1);
        } else {
//            tagetTime = DateUtils.getMonthBackString(2, "yyyy-MM");
            calendar.add(Calendar.MONTH, 2);
        }
        return calendar;
    }


    private Calendar StringToClender(Date date) {
        Calendar calendar = Calendar.getInstance();

        calendar.setTime(date);
        return calendar;
    }

    public String CalendarToString(Calendar calendar) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        Date resultDate = calendar.getTime(); // 结果
        return sdf.format(resultDate);
    }

    private String getNextQuarter() {
        Calendar calendar = Calendar.getInstance();
        int mouth = Calendar.getInstance().get(Calendar.MONTH) + 1;
        int year = Calendar.getInstance().get(Calendar.YEAR);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        if (mouth >= 1 && mouth <= 3) {
            calendar.set(year, 4, 1);
            Date resultDate = calendar.getTime(); // 结果
            return sdf.format(resultDate);
        } else if (mouth >= 4 && mouth <= 6) {
            calendar.set(year, 7, 1);
            Date resultDate = calendar.getTime(); // 结果
            return sdf.format(resultDate);
        } else if (mouth >= 7 && mouth <= 9) {
            calendar.set(year, 10, 1);
            Date resultDate = calendar.getTime(); // 结果
            return sdf.format(resultDate);
        } else if (mouth >= 10 && mouth <= 12) {
            calendar.set(year + 1, 1, 1);
            Date resultDate = calendar.getTime(); // 结果
            return sdf.format(resultDate);
        } else {
            return "";
        }
    }

}